package com.example.study.commen.print;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import javax.print.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.Sides;
import java.awt.print.PrinterJob;
import java.io.*;

public class Test {

    public static void main(String[] args) {
        xxx();
    }

    public static void xxx() {
//        zzz("C:\\Users\\去\\Desktop\\通信文档总结\\光照度_09.jpg");
//        zzz("C:\\Users\\去\\Pictures\\Saved Pictures\\234.jpg");
//        zzz("C:\\Users\\去\\Pictures\\Saved Pictures\\789.pdf");
//        zzz("C:\\Users\\去\\Desktop\\通信文档总结\\1111.jpeg");
//        zzz("C:\\Users\\去\\Desktop\\通信文档总结\\功能支持需求描述.docx");


//        File file = new File("C:\\Users\\去\\Desktop\\通信文档总结\\功能支持需求描述.docx");
        String printerName = "Generic / Text Only";//打印机名包含字串
//        try {
//            JPGPrint(file, printerName);
//        } catch (PrintException e) {
//            throw new RuntimeException(e);
//        }
//        printWord("C:\\Users\\去\\Desktop\\通信文档总结\\功能支持需求描述.docx", printerName);
//        wordToPdf("C:\\Users\\去\\Desktop\\通信文档总结\\123.docx","C:\\Users\\去\\Desktop\\通信文档总结\\123.pdf");
        try {
            zzz();
        } catch (IOException e) {
            System.out.println("失败"+e.getMessage());
            throw new RuntimeException(e);

        }
    }

    private static void zzz() throws IOException {
        FileInputStream fileInputStream = new FileInputStream("C:\\Users\\去\\Desktop\\通信文档总结\\123.docx");
        XWPFDocument xwpfDocument = new XWPFDocument(fileInputStream);
        PdfOptions pdfOptions = PdfOptions.create();
        FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\去\\Desktop\\通信文档总结\\234.pdf");
        PdfConverter.getInstance().convert(xwpfDocument,fileOutputStream,pdfOptions);
        fileInputStream.close();
        fileOutputStream.close();


    }

    public static void wordToPdf(String source, String toFile) {
//该方法只可以操作2003版的word（据说jacob只能这样，没亲自试过）
//txt格式的文件也可以用该方法转换成pdf（亲测可以成功，ps：偶然发现的）

        String filename = source;
        String toFilename = toFile;
        // System.out.println("启动Word");
        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        try {
            //启动word应用程序(Microsoft Office Word 2003)
            app = new ActiveXComponent("Word.Application");
            //// 设置word应用程序不可见
            app.setProperty("Visible", false);
            // documents表示word程序的所有文档窗口，（word是多文档应用程序）
            Dispatch docs = app.getProperty("Documents").toDispatch();
            //System.out.println("打开文档" + filename);
            //打开要转换的word文件 ,作为pdf格式保存到临时文件
            Dispatch doc = Dispatch.call(docs,//
                    "Open", //
                    filename,// FileName
                    false,// ConfirmConversions
                    true // ReadOnly
            ).toDispatch();

            System.out.println("转换文档到PDF: " + toFilename);
            File tofile = new File(toFilename);
            if (tofile.exists()) {
                tofile.delete();
            }

            Dispatch.call(doc,//
                    "SaveAs", //
                    toFilename, // FileName);
                    // 关闭word文件
                    Dispatch.call(doc, "Close", false));
            long end = System.currentTimeMillis();
            System.out.println("转换完成..用时：" + (end - start) + "ms.");
        } catch (Exception e) {
            System.out.println("========Error:文档转换失败：" + e.getMessage());
        } finally {
            if (app != null)
                //关闭word应用程序
                app.invoke("Quit", true);
        }
    }

// 传入文件和打印机名称

    /**
     * 打印图片
     *
     * @param file
     * @param printerName
     * @throws PrintException
     */
    public static void JPGPrint(File file, String printerName) throws PrintException {


        if (file == null) {


            System.err.println("缺少打印文件");


        }


        InputStream fis = null;


        try {


            // 设置打印格式，如果未确定类型，可选择autosense


            DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;


            // 设置打印参数


            PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();


            aset.add(new Copies(1)); //份数


            //aset.add(MediaSize.ISO.A4); //纸张


            // aset.add(Finishings.STAPLE);//装订


            aset.add(Sides.ONE_SIDED);//单双面


            // 定位打印服务


            PrintService printService = null;


            if (printerName != null) {


                //获得本台电脑连接的所有打印机
                PrintService[] printServices = PrinterJob.lookupPrintServices();
                if (printServices == null || printServices.length == 0) {
                    System.out.print("打印失败，未找到可用打印机，请检查。");
                    return;
                }
                //匹配指定打印机
                for (int i = 0; i < printServices.length; i++) {
                    System.out.println(printServices[i].getName());
                    if (printServices[i].getName().contains(printerName)) {
                        printService = printServices[i];
                        break;
                    }
                }
                if (printService == null) {
                    System.out.print("打印失败，未找到名称为" + printerName + "的打印机，请检查。");
                    return;
                }
            }
            fis = new FileInputStream(file); // 构造待打印的文件流
            Doc doc = new SimpleDoc(fis, flavor, null);
            DocPrintJob job = printService.createPrintJob(); // 创建打印作业
            job.print(doc, aset);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } finally {
            // 关闭打印的文件流
            if (fis != null) {
                try {
                    fis.close();

                } catch (IOException e) {


                    e.printStackTrace();


                }


            }


        }


    }


    public static void printWord(String filePath, String printerName) {


//        初始化线程


        ComThread.InitSTA();


        ActiveXComponent word = new ActiveXComponent("Word.Application");


        //设置打印机名称


        word.setProperty("ActivePrinter", new Variant(printerName));


        // 这里Visible是控制文档打开后是可见还是不可见，若是静默打印，那么第三个参数就设为false就好了


        Dispatch.put(word, "Visible", new Variant(false));


        // 获取文档属性


        Dispatch document = word.getProperty("Documents").toDispatch();


        // 打开激活文挡


        Dispatch doc = Dispatch.call(document, "Open", filePath).toDispatch();


        //Dispatch doc = Dispatch.invoke(document, "Open", Dispatch.Method,


        //  new Object[] { filePath }, new int[1]).toDispatch();


        try {


            Dispatch.callN(doc, "PrintOut");


            System.out.println("打印成功！");


        } catch (Exception e) {


            e.printStackTrace();


            System.out.println("打印失败");


        } finally {


            try {


                if (doc != null) {


                    Dispatch.call(doc, "Close", new Variant(0));//word文档关闭


                }


            } catch (Exception e2) {


                e2.printStackTrace();


            }


            //退出


            word.invoke("Quit", new Variant[0]);


            //释放资源


            ComThread.Release();


            ComThread.quitMainSTA();


        }


    }
}
